/**
 * Copyright 2009 University of Washington This code is released under the GPL version 3 - with a copy of the license
 * included
 * 
 * @author Maya Hao Li
 * 
 */
package seedpod.webapp.view.seedpodwidgets;

/**
 * A yes/no check box widget
 * 
 */
import seedpod.exceptions.InvalidWidgetException;
import seedpod.model.AVPair;
import seedpod.model.ProtegeValueType;
import seedpod.model.SeedpodModel.RdbCls.FormWidget;
import seedpod.model.SeedpodModel.RdbCls.ViewWidget;
import seedpod.webapp.view.htmlwidget.CheckBoxInput;

public class CheckBox extends LimsWidget {

	public CheckBox() {
	// TODO Auto-generated constructor stub
	}

	public CheckBox(AVPair avpair) {
		super( avpair );
	}

	@Override
	public String doEdit() {
		return render();
	}

	@Override
	public String doView() {
		return render();
	}

	@Override
	public Boolean getData() {
		return toBoolean( _avPair.getValue() );
	}

	@Override
	public FormWidget getFormWidgetType() {
		return FormWidget.CHECKBOX;
	}

	@Override
	public ViewWidget getViewWidgetType() {
		return ViewWidget.CHECKBOX;
	}

	@Override
	public String render() {
		CheckBoxInput cbInput = new CheckBoxInput( _widgetID, Boolean.TRUE.toString(), getData() );
		return cbInput.render();
	}

	private Boolean toBoolean( Object data ) {
		if ( data == null ) return null;
		String boolString = (String)data;

		if ( boolString.equalsIgnoreCase( "t" ) || boolString.equalsIgnoreCase( "true" ) )
			return Boolean.TRUE;
		else return Boolean.FALSE;
	}

	@Override
	public void validateWidget() throws InvalidWidgetException {
		if ( !getAttribute().getProtegeValueType().equals( ProtegeValueType.Boolean ) )
			throw new InvalidWidgetException( "This widget supports boolean value only." );
	}
}